package cn.llming.auth.interceptor;

import cn.llming.auth.domain.RoleMenu;
import cn.llming.auth.mapper.PermissionMapper;
import cn.llming.auth.util.BasePermission;
import cn.llming.org.domain.Employee;
import cn.llming.vo.result.BaseMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            response.getWriter().write("{\"success\":false,\"message\":\"nologin\"}");
            return false;
        }
        Object o = BaseMap.resultMap.get(token);

        if(Objects.isNull(o)){
            response.getWriter().write("{\"success\":false,\"message\":\"nologin\"}");
            return false;
        }
        Employee employee=(Employee)o;

        //鉴权
        //1.先通过用户发起请求，拿到对应的controller方法
        if(handler instanceof HandlerMethod){
            Method method = ((HandlerMethod) handler).getMethod();
            BasePermission annotation = method.getAnnotation(BasePermission.class);
            String userTo=method.getDeclaringClass().getSimpleName()+":"+method.getName();
            //2.再判断方法上有没有权限注解 有就拦截，没有放行
            if(Objects.isNull(annotation)){
                return true;
            }
            //3.通过查询当前用户使用权限
           List<String> permissionSns= permissionMapper.getEmpInfoPermissionByEmpId(employee.getId());
            //将当前用户拥有权限与访问权限进行对比，contains
            if(!permissionSns.contains(userTo)){
                System.out.println("拦截了");
                response.getWriter().write("{\"success\":false,\"message\":\"noPermission\"}");
                return false;
            }
        }

        return true;
    }
}
